<template>
  <div class="intercept-dashboard">
    <header class="mb-8">
      <h1 class="glow-text">拦截管理</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <!-- 拦截状态卡片 -->
    <div class="card mb-8">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-medium">拦截状态</h2>
        <div class="flex space-x-2">
          <button 
            v-if="!interceptStatus.is_running" 
            @click="showStartInterceptModal = true" 
            class="btn btn-primary"
          >
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            开始拦截
          </button>
          <button 
            v-else 
            @click="stopIntercept" 
            class="btn btn-danger"
          >
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"></path>
            </svg>
            停止拦截
          </button>
          <button @click="refreshStatus" class="btn btn-outline">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
            刷新
          </button>
        </div>
      </div>

      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="bg-dark-darker p-6 rounded-lg">
          <div class="flex items-center mb-4">
            <div class="w-3 h-3 rounded-full mr-2" :class="interceptStatus.is_running ? 'bg-accent-blue animate-pulse' : 'bg-accent-pink'"></div>
            <h3 class="text-lg font-medium">拦截状态</h3>
          </div>
          <div class="text-2xl font-bold mb-2">{{ interceptStatus.is_running ? '正在拦截' : '未拦截' }}</div>
          <div class="text-light-dark">
            <div v-if="interceptStatus.is_running">
              <div>拦截规则数: {{ interceptStatus.rules?.length || 0 }}</div>
              <div>开始时间: {{ formatTime(interceptStatus.start_time) }}</div>
            </div>
            <div v-else>
              上次拦截时间: {{ interceptStatus.last_intercept_time ? formatTime(interceptStatus.last_intercept_time) : '无记录' }}
            </div>
          </div>
        </div>

        <div class="bg-dark-darker p-6 rounded-lg">
          <h3 class="text-lg font-medium mb-4">拦截统计</h3>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <div class="text-light-dark mb-1">拦截规则数</div>
              <div class="text-2xl font-bold">{{ stats.ruleCount }}</div>
            </div>
            <div>
              <div class="text-light-dark mb-1">拦截请求数</div>
              <div class="text-2xl font-bold">{{ stats.interceptCount }}</div>
            </div>
            <div>
              <div class="text-light-dark mb-1">今日新增</div>
              <div class="text-2xl font-bold">{{ stats.todayCount }}</div>
            </div>
            <div>
              <div class="text-light-dark mb-1">平均响应时间</div>
              <div class="text-2xl font-bold">{{ stats.avgResponseTime }}ms</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速导航 -->
    <div class="grid grid-cols-1 md:grid-cols-1 gap-6 mb-8">
      <router-link to="/intercept/rules" class="tech-card hover:border-primary transition-all duration-300">
        <div class="flex items-center mb-4">
          <svg class="w-6 h-6 mr-3 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
          </svg>
          <h3 class="text-xl font-medium">拦截规则</h3>
        </div>
        <p class="text-light-dark mb-4">管理拦截规则，包括查看、清除拦截规则。</p>
        <div class="text-primary">查看拦截规则 →</div>
      </router-link>
    </div>

    <!-- 当前拦截规则 -->
    <div class="card">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-medium">当前拦截规则</h2>
        <div class="flex space-x-2">
          <router-link to="/intercept/rules" class="btn btn-outline text-sm">查看全部</router-link>
          <button @click="clearRules" class="btn btn-danger text-sm">
            <svg class="w-4 h-4 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
            </svg>
            清除所有规则
          </button>
        </div>
      </div>

      <div v-if="loadingRules" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>

      <div v-else-if="rules.length === 0" class="text-center py-12 text-light-dark">
        暂无拦截规则
      </div>

      <div v-else class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-dark-light">
              <th class="py-3 px-4 text-left">服务名称</th>
              <th class="py-3 px-4 text-left">服务端口</th>
              <th class="py-3 px-4 text-left">代理端口</th>
              <th class="py-3 px-4 text-left">创建时间</th>
              <th class="py-3 px-4 text-left">状态</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="rule in rules"
              :key="rule.id"
              class="border-b border-dark-light hover:bg-dark-darker"
            >
              <td class="py-3 px-4">{{ rule.service_name }}</td>
              <td class="py-3 px-4">{{ rule.service_port }}</td>
              <td class="py-3 px-4">{{ rule.proxy_port }}</td>
              <td class="py-3 px-4 text-light-dark">{{ formatTime(rule.created_at) }}</td>
              <td class="py-3 px-4">
                <span :class="{
                  'badge badge-blue': rule.is_active,
                  'badge badge-yellow': !rule.is_active
                }">{{ rule.is_active ? '活跃' : '非活跃' }}</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 开始拦截弹窗 -->
    <div v-if="showStartInterceptModal" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-lg cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">开始拦截</h2>
            <button @click="showStartInterceptModal = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-6">
            <label class="block text-light-dark mb-2">选择服务</label>
            <div v-if="loadingServices" class="flex justify-center items-center py-4">
              <div class="animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-primary"></div>
            </div>
            <div v-else-if="services.length === 0" class="text-center py-4 text-light-dark">
              暂无服务，请先添加服务
            </div>
            <div v-else class="max-h-60 overflow-y-auto bg-dark-darker rounded-lg p-2">
              <div
                v-for="service in services"
                :key="service._id"
                class="flex items-center p-2 hover:bg-dark-light rounded-md"
              >
                <input
                  type="checkbox"
                  :id="`service-${service._id}`"
                  v-model="interceptForm.service_ids"
                  :value="service._id"
                  class="mr-2"
                />
                <label :for="`service-${service._id}`" class="flex-1 cursor-pointer">
                  <div>{{ service.service_name }}</div>
                  <div class="text-sm text-light-dark">{{ service.service_ip }}:{{ service.service_port }}</div>
                </label>
              </div>
            </div>
          </div>

          <div class="flex justify-end">
            <button @click="showStartInterceptModal = false" class="btn btn-outline mr-2">取消</button>
            <button @click="startIntercept" class="btn btn-primary" :disabled="startingIntercept">
              <span v-if="startingIntercept">开始中...</span>
              <span v-else>开始拦截</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { interceptApi, servicesApi } from '../../api';

// 状态变量
const loading = ref(false);
const loadingRules = ref(false);
const loadingServices = ref(false);
const startingIntercept = ref(false);
const showStartInterceptModal = ref(false);

// 拦截状态
const interceptStatus = ref({
  is_running: false,
  rules: [] as any[],
  start_time: '',
  last_intercept_time: ''
});

// 统计数据
const stats = ref({
  ruleCount: 0,
  interceptCount: 0,
  todayCount: 0,
  avgResponseTime: 0
});

// 拦截规则列表
const rules = ref<any[]>([]);

// 服务列表
const services = ref<any[]>([]);

// 拦截表单
const interceptForm = ref({
  service_ids: [] as string[]
});

// 获取拦截状态
const fetchInterceptStatus = async () => {
  try {
    loading.value = true;
    
    // 这里应该有一个获取拦截状态的API，暂时使用模拟数据
    interceptStatus.value = {
      is_running: true,
      rules: [
        {
          id: '1',
          service_name: 'user-service',
          service_port: 8080,
          proxy_port: 9080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '2',
          service_name: 'order-service',
          service_port: 8081,
          proxy_port: 9081,
          is_active: true,
          created_at: new Date().toISOString()
        }
      ],
      start_time: new Date(Date.now() - 3600000).toISOString(),
      last_intercept_time: new Date(Date.now() - 86400000).toISOString()
    };
  } catch (error) {
    console.error('获取拦截状态失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const fetchStats = async () => {
  try {
    // 这里应该有一个获取统计数据的API，暂时使用模拟数据
    stats.value = {
      ruleCount: 5,
      interceptCount: 128,
      todayCount: 24,
      avgResponseTime: 45.8
    };
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取拦截规则列表
const fetchRules = async () => {
  try {
    loadingRules.value = true;
    const response = await interceptApi.getInterceptRules();
    
    if (response && typeof response === 'object' && Array.isArray(response.rules)) {
      rules.value = response.rules;
    } else {
      // 模拟数据
      rules.value = [
        {
          id: '1',
          service_name: 'user-service',
          service_port: 8080,
          proxy_port: 9080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '2',
          service_name: 'order-service',
          service_port: 8081,
          proxy_port: 9081,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          id: '3',
          service_name: 'payment-service',
          service_port: 8082,
          proxy_port: 9082,
          is_active: false,
          created_at: new Date().toISOString()
        }
      ];
    }
  } catch (error) {
    console.error('获取拦截规则列表失败:', error);
  } finally {
    loadingRules.value = false;
  }
};

// 获取服务列表
const fetchServices = async () => {
  try {
    loadingServices.value = true;
    const response = await servicesApi.getAll();
    
    if (response && typeof response === 'object' && Array.isArray(response.services)) {
      services.value = response.services;
    } else {
      // 模拟数据
      services.value = [
        {
          _id: '1',
          service_name: 'user-service',
          service_ip: '10.0.0.1',
          service_port: 8080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          _id: '2',
          service_name: 'order-service',
          service_ip: '10.0.0.2',
          service_port: 8081,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          _id: '3',
          service_name: 'payment-service',
          service_ip: '10.0.0.3',
          service_port: 8082,
          is_active: true,
          created_at: new Date().toISOString()
        }
      ];
    }
  } catch (error) {
    console.error('获取服务列表失败:', error);
  } finally {
    loadingServices.value = false;
  }
};

// 开始拦截
const startIntercept = async () => {
  if (interceptForm.value.service_ids.length === 0) {
    alert('请选择至少一个服务');
    return;
  }

  try {
    startingIntercept.value = true;
    await interceptApi.startIntercept({
      service_ids: interceptForm.value.service_ids
    });
    
    showStartInterceptModal.value = false;
    interceptForm.value.service_ids = [];
    
    // 刷新状态
    await Promise.all([
      fetchInterceptStatus(),
      fetchRules()
    ]);
  } catch (error: any) {
    console.error('开始拦截失败:', error);
    alert(`开始拦截失败: ${error.response?.data?.error || error.message}`);
  } finally {
    startingIntercept.value = false;
  }
};

// 停止拦截
const stopIntercept = async () => {
  if (!confirm('确定要停止拦截吗？')) return;

  try {
    loading.value = true;
    await interceptApi.stopIntercept({});
    
    // 刷新状态
    await Promise.all([
      fetchInterceptStatus(),
      fetchRules()
    ]);
  } catch (error: any) {
    console.error('停止拦截失败:', error);
    alert(`停止拦截失败: ${error.response?.data?.error || error.message}`);
  } finally {
    loading.value = false;
  }
};

// 清除所有规则
const clearRules = async () => {
  if (!confirm('确定要清除所有拦截规则吗？此操作不可恢复。')) return;

  try {
    loadingRules.value = true;
    await interceptApi.clearInterceptRules();
    
    // 刷新状态
    await Promise.all([
      fetchInterceptStatus(),
      fetchRules()
    ]);
  } catch (error: any) {
    console.error('清除拦截规则失败:', error);
    alert(`清除拦截规则失败: ${error.response?.data?.error || error.message}`);
  } finally {
    loadingRules.value = false;
  }
};

// 刷新状态
const refreshStatus = async () => {
  await Promise.all([
    fetchInterceptStatus(),
    fetchRules()
  ]);
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 定时刷新
let refreshInterval: number | null = null;

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchInterceptStatus(),
    fetchStats(),
    fetchRules(),
    fetchServices()
  ]);

  // 设置定时刷新
  refreshInterval = window.setInterval(() => {
    if (interceptStatus.value.is_running) {
      fetchInterceptStatus();
      fetchRules();
    }
  }, 10000);
});

onUnmounted(() => {
  if (refreshInterval !== null) {
    clearInterval(refreshInterval);
  }
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
